var filename; //视频标题名(下载视频的文件名)
var audioBaseUrl; // 音频url
var videoUrls = []; // 用于存储视频 URL 的数组
var videoBaseUrlStandard; //视频url
var videoBaseUrlUnderscore; //视频url

let ontrol_bottom = document.querySelector(".bpx-player-control-bottom");
console.log(ontrol_bottom);
if (ontrol_bottom) {
  // 设置延时时间，这里设置为 1 秒，你可以按需修改
  const delayTime = 2000;
  setTimeout(() => {
    const bottomRight = ontrol_bottom.querySelector(
      ".bpx-player-control-bottom-right"
    );
    if (bottomRight) {
      const menu = bottomRight.querySelector(
        ".bpx-player-ctrl-playbackrate-menu"
      );
      if (menu) {
        // 定义要添加的播放速率选项
        const playbackRates = [2.5, 3, 3.5, 4];
        // <li class="bpx-player-ctrl-playbackrate-menu-item " data-value="2">2.0x</li>
        for (let rate of playbackRates) {
          // 创建 li 元素
          const listItem = document.createElement("li");
          listItem.classList.add("bpx-player-ctrl-playbackrate-menu-item");
          listItem.setAttribute("data-value", rate.toString());
          listItem.textContent = `${rate}x`;
          // 将 li 元素添加到 menu 中
          // 获取 menu 的第一个子节点
          const firstChild = menu.firstChild;
          // 将 li 元素插入到 menu 的最前面
          menu.insertBefore(listItem, firstChild);
        }
      } else {
        console.log("未找到 .bpx-player-ctrl-playbackrate-menu 元素");
      }
    } else {
      console.log("未找到 .bpx-player-control-bottom-right 元素");
    }
  }, delayTime);
} else {
  console.log("未找到 .bpx-player-control-bottom 元素");
}

// 获取整个文档的 HTML 字符串
const document_data = document.documentElement.outerHTML;
// console.log(document_data);
// 正则表达式
const regex = /<script>window.__playinfo__=(.*?)<\/script>/s;
const match = document_data.match(regex);
if (match) {
  const playinfoContent = match[1];
  // console.log(playinfoContent);
  try {
    const playinfo = JSON.parse(playinfoContent);
    console.log(playinfo);

    setTimeout(() => {
      // 插入html
      const htmlToInsert = `
      <div
            class="bpx-player-ctrl-btn bpx-player-ctrl-quality video"
            role="button"
            aria-label="清晰度"
            tabindex="0"
          
            
          >
            <a
              title="无"
              download=""
              href=""
              style="color: #fff;"
            >
              视频
            </a>
          </div>
            <div
            class="bpx-player-ctrl-btn bpx-player-ctrl-quality audio"
            role="button"
            aria-label="清晰度"
            tabindex="0"
            
          >
            <a
              title="无"
              download=""
              href=""
              style="color: #fff;"
            >
              音频
            </a>
          </div>
      `;

      //下载按钮
      const toolbar = document.querySelector(
        ".bpx-player-control-bottom-right"
      );
      if (toolbar) {
        toolbar.insertAdjacentHTML("afterbegin", htmlToInsert);
      }
    }, 2000);

    const title_dom = document.querySelector(".video-info-title-inner");
    const title = title_dom
      .querySelector(".video-title.special-text-indent")
      .getAttribute("title");
    filename = title.replace(/[^\u4e00-\u9fa5]/g, "");
    console.log(filename);

    // 从 playinfo 对象中提取视频和音频的基础 URL 以及备用 URL
    const playInfo = playinfo;
    const firstVideo = playInfo["data"]["dash"]["video"][0];
    const firstAudio = playInfo["data"]["dash"]["audio"][0];

    videoBaseUrlStandard = firstVideo["baseUrl"];
    videoBaseUrlUnderscore = firstVideo["base_url"];
    audioBaseUrl = firstAudio["baseUrl"];

    const audioBackupUrlsStandard = firstVideo["backupUrl"];
    const audioBackupUrlsUnderscore = firstVideo["backup_url"];

    // 将视频基础 URL 添加到数组
    videoUrls.push(videoBaseUrlStandard);
    videoUrls.push(videoBaseUrlUnderscore);

    // 将备用 URL 添加到数组
    if (Array.isArray(audioBackupUrlsStandard)) {
      audioBackupUrlsStandard.forEach((url) => videoUrls.push(url));
    }
    if (Array.isArray(audioBackupUrlsUnderscore)) {
      audioBackupUrlsUnderscore.forEach((url) => videoUrls.push(url));
    }

    // 打印存储所有视频 URL 的数组
    console.log(videoUrls);

    setTimeout(() => {
      const toolbar = document.querySelector(
        ".bpx-player-control-bottom-right"
      );
      const videohref = toolbar.querySelector(".video").querySelector("a");
      console.log(videohref);
      videohref.download = filename + ".mp4";
      videohref.href = videoBaseUrlStandard;
      videohref.title = filename + ".mp4";

      const audiohref = toolbar.querySelector(".audio").querySelector("a");
      console.log(audiohref);
      audiohref.download = filename + ".mp3";
      audiohref.href = audioBaseUrl;
      audiohref.title = filename + ".mp3";
    }, 4000);
    // downloadVideo(url, filename)
  } catch (error) {
    console.error("解析 JSON 时出错:", error);
  }
} else {
  console.log("未找到匹配的内容");
}

// !调整页面元素 “评论”移动位置
// 防止页面抖动
const style = document.createElement("style");
style.textContent = `
        html {
          overflow-y: scroll !important;
        }
      `;
document.head.appendChild(style);

// 检测URL变化和DOM变化
let currentUrl = window.location.href;
const targetNode = document.body;
const config = { childList: true, subtree: true };

const callback = function (mutationsList, observer) {
  if (window.location.href !== currentUrl) {
    currentUrl = window.location.href;

    // 使用requestAnimationFrame来减少闪烁

    // 使用replace而不是直接赋值，避免创建新的历史记录
    // window.location.replace(currentUrl);

    // 延迟执行删除广告和确保按钮存在的操作
    requestAnimationFrame(() => {
      delete_ad();
      ensureButtonsExist();
    });
  }
};

const observer = new MutationObserver(callback);
observer.observe(targetNode, config);

// 检查并插入按钮
function ensureButtonsExist() {
  // 创建要插入的HTML结构
  const htmlToInsert = `
    <div class="button-row" style="
      display: flex;
      width: 100%;
      gap: 1px;
      margin: 10px 0;
      background: #f0f0f0;
      border:1px solid rgba(0,0,0,0.1);
      border-radius: 8px;
      overflow: hidden;
      box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    ">
      <button class="tab-button active" data-tab="original" style="
        flex: 1;
        min-width: 0;
        padding: 10px 0;
        cursor: pointer;
        pointer-events: auto;
        border:1px solid rgba(0,0,0,0.1);
        background:  rgb(241, 242, 243)
        color: #333;
        font-weight: 500;
        transition: all 0.3s ease;
        border-right: 1px solid #eee;
      ">原</button>
      <button class="tab-button" data-tab="comment" style="
        flex: 1;
        min-width: 0;
        padding: 10px 0;
        cursor: pointer;
        pointer-events: auto;
        border:1px solid rgba(0,0,0,0.1);
        background:  rgb(241, 242, 243);
        color: #333;
        font-weight: 500;
        transition: all 0.3s ease;
        border-right: 1px solid #eee;
      ">评论</button>
  
    </div>
    `;
  const danmukuBox = document.querySelector("#danmukuBox");
  const existingButtonRow = document.querySelector(".button-row");

  // 如果按钮不存在，且danmukuBox存在，则插入
  if (!existingButtonRow && danmukuBox) {
    danmukuBox.insertAdjacentHTML("beforebegin", htmlToInsert);
    setupButtonEvents(); // 重新绑定事件
  }
}

// 优化后的元素显示设置函数
function setElementsDisplay(elements, displayValue) {
  if (!elements) return;

  // 支持单个元素、NodeList或数组
  const elementsArray = elements.length ? Array.from(elements) : [elements];

  elementsArray.forEach((el) => {
    if (el && el.style) {
      el.style.display = displayValue;
    }
  });
}

// 设置切换按钮功能
function setupToggleButton() {
  const toggle_btn_text = document.querySelectorAll(".toggle-btn-text");
  if (toggle_btn_text.length < 2) return;

  toggle_btn_text[1].style.pointerEvents = "auto";
  let originalHeight = null;

  toggle_btn_text[1].addEventListener("click", (e) => {
    const textContainer = document.querySelectorAll(".desc-info-text");
    if (textContainer.length < 2) return;

    const parentElement = textContainer[1].parentElement;
    if (!parentElement) return;

    if (originalHeight === null) {
      originalHeight =
        parentElement.style.height ||
        window.getComputedStyle(parentElement).height;
    }

    const isExpanded =
      parentElement.style.height === `${textContainer[1].offsetHeight + 5}px`;

    parentElement.style.height = isExpanded
      ? originalHeight === "auto"
        ? ""
        : originalHeight
      : `${textContainer[1].offsetHeight + 5}px`;
  });
}
// todo 删除广告
function delete_ad() {
  // 使用解构赋值定义所有选择器
  const selectors = {
    // 单个元素选择器
    single: [".video-card-ad-small", "#slide_ad", ".bpx-player-video-area"],
    // 多个元素选择器
    multiple: [".ad-report", "#notice", ".activity-m-v1"],
  };

  // 处理单个元素
  selectors.single.forEach((selector) => {
    const element = document.querySelector(selector);
    if (element) {
      if (selector === ".bpx-player-video-area") {
        // 特殊处理播放器边框
        element.style.borderRight = "1px solid #fff";
      } else {
        setElementsDisplay(element, "none");
      }
    }
  });

  // 处理多个元素
  selectors.multiple.forEach((selector) => {
    const elements = document.querySelectorAll(selector);
    setElementsDisplay(elements, "none");
  });
}

// 本地存储键名
const TAB_STORAGE_KEY = "currentTab";
function setupButtonEvents() {
  const buttons = document.querySelectorAll(".tab-button");

  // 从本地存储恢复状态
  const savedTab = localStorage.getItem(TAB_STORAGE_KEY);
  if (savedTab) {
    const savedButton = document.querySelector(
      `.tab-button[data-tab="${savedTab}"]`
    );
    if (savedButton) {
      buttons.forEach((btn) => btn.classList.remove("active"));
      savedButton.classList.add("active");

      // 触发对应的标签页内容切换
      if (savedTab === "comment") {
        handleCommentTab();
      } else if (savedTab === "original") {
        handleOriginalTab();
      }
    }
  } else {
    // 默认选中第一个按钮（如果没有保存的状态）
    buttons[0]?.classList.add("active");
  }

  // 设置按钮点击事件
  buttons.forEach((button) => {
    button.addEventListener(
      "click",
      function (e) {
        e.stopPropagation();
        e.preventDefault();

        // 更新按钮状态
        buttons.forEach((btn) => btn.classList.remove("active"));
        this.classList.add("active");

        // 获取并保存当前标签类型
        const tabType = this.getAttribute("data-tab");
        localStorage.setItem(TAB_STORAGE_KEY, tabType);

        // console.log(`切换到 ${tabType} 标签页`);

        // 切换内容
        if (tabType === "comment") {
          handleCommentTab();
        } else if (tabType === "original") {
          handleOriginalTab();
          delete_ad();
        }
      },
      { passive: false }
    );
  });
}

// todo 切换
let toggleBtnListenerAdded = false; // 标记是否已添加监听器

// 处理评论标签页
function handleCommentTab() {
  if (!document.querySelector(".copy-v-desc")) {
    const originalCommentApp = document.querySelector("#commentapp");
    window.OLD_COMMENT_APP = originalCommentApp.cloneNode(true);

    const stickyContainer = document.querySelector(
      ".right-container-inner.scroll-sticky"
    );
    const v_desc = document.querySelector("#v_desc");
    const basic_desc_info = document.querySelector(".video-tag-container");
    const rcmd_tab = document.querySelector(".rcmd-tab");

    if (!originalCommentApp || !stickyContainer) return;

    const clonedV_desc = v_desc?.cloneNode(true);
    const clonedBasic_desc_info = basic_desc_info?.cloneNode(true);
    const clonedCommentApp = originalCommentApp.cloneNode(true);

    const clones = [
      clonedV_desc,
      clonedBasic_desc_info,
      clonedCommentApp,
    ].filter(Boolean);

    setElementsDisplay(
      [originalCommentApp, v_desc, basic_desc_info, rcmd_tab],
      "none"
    );

    // 定义要给每个元素添加的不同class
    const classNames = ["copy-v-desc", "copy-basic-info", "copy-comment-app"];

    // 移除克隆元素的ID避免重复，并添加各自的class
    clones.forEach((clone, index) => {
      // clone.removeAttribute("id"); // 移除ID
      clone.classList.add(classNames[index]); // 添加对应的class
    });

    // 克隆元素
    clones.forEach((clone) => {
      stickyContainer.appendChild(clone);
    });

    // 只添加一次事件监听器
    if (!toggleBtnListenerAdded) {
      setupToggleButton();
      toggleBtnListenerAdded = true;
    }
    delete_ad();
  } else {
    setElementsDisplay(
      [
        document.querySelector(".copy-v-desc"),
        document.querySelector(".copy-basic-info"),
        document.querySelector(".copy-comment-app"),
      ],
      ""
    );
    // 显示原始元素
    setElementsDisplay(
      [
        document.querySelector("#commentapp"),
        document.querySelector("#v_desc"),
        document.querySelector(".video-tag-container"),
        document.querySelector(".rcmd-tab"),
      ],
      "none"
    );
  }
}

// 处理原始标签页
function handleOriginalTab() {
  -(
    // 显示原始元素
    setElementsDisplay(
      [
        document.querySelector("#commentapp"),
        document.querySelector("#v_desc"),
        document.querySelector(".video-tag-container"),
        document.querySelector(".rcmd-tab"),
      ],
      ""
    )
  );

  setElementsDisplay(
    [
      document.querySelector(".copy-v-desc"),
      document.querySelector(".copy-basic-info"),
      document.querySelector(".copy-comment-app"),
    ],
    "none"
  );
  delete_ad();
}

setTimeout(() => {
  delete_ad();

  // 添加悬停和激活样式
  const style = document.createElement("style");
  style.textContent = `
    .tab-button:hover {
      background: #f8f8f8 !important;
      color: #1890ff !important;
    }
    .tab-button.active {
      background: #1890ff !important;
      color: white !important;
    }
  `;
  document.head.appendChild(style);

  // 使用MutationObserver监听DOM变化
  const observer = new MutationObserver((mutations) => {
    mutations.forEach((mutation) => {
      // 检查是否有节点被移除

      ensureButtonsExist(); // 如果按钮被移除，重新插入
    });
  });

  // 初始检查
  ensureButtonsExist();
  let right_container = document.querySelector(".right-container");
  console.log(right_container);
  observer.observe(right_container, {
    childList: true,
    subtree: true,
  });
}, 2500);
